﻿namespace SourceCodeRepository.Web.Controllers
{
    using System.Web.Mvc;
    using Infra.Logging;
    using StructureMap;

    /// <summary>
    /// Factory class for the Controllers resolving dependencies with StructureMap
    /// </summary>
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// Gets or sets the logger.
        /// </summary>
        /// <value>The logger.</value>
        private ILog Logger { get; set; }
        
        /// <summary>
        /// Initializes a new instance of the <see cref="StructureMapControllerFactory"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public StructureMapControllerFactory(ILog logger)
        {
            this.Logger = logger;
        }
        
        /// <summary>
        /// Gets the controller instance.
        /// </summary>
        /// <param name="controllerType">Type of the controller.</param>
        /// <returns></returns>
        protected override IController GetControllerInstance(System.Type controllerType)
        {
            IController result = null;
            try
            {
                if (controllerType != null)
                {
                    this.Logger.WriteMessage(string.Format("Creating Controller: {0}", controllerType.ToString()));
                    result = ObjectFactory.GetInstance(controllerType) as Controller;
                }

            }
            catch (StructureMapException)
            {
                this.Logger.WriteMessage(ObjectFactory.WhatDoIHave());
                throw;
            }

            return result;
        }
    }
}
